package com.wan.tool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

public class DBManage {
	private final int BUFFER_SIZE = 400000;
	public static final String DB_NAME = "yqbword.db"; // 保存的数据库文件名
	public static final String PACKAGE_NAME = "com.wan.word";
	public static final String DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/" + PACKAGE_NAME; // 在手机里存放数据库的位置

	private SQLiteDatabase database;
	private Context context;

	public DBManage(Context context) {
		this.context = context;
	}

	public void openDatabase() {
		this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
	}

	public void copyDatabase() {
		String dbfile = DB_PATH + "/" + DB_NAME;
		copyDatabase(dbfile);
	}

	private void copyDatabase(String dbfile) {
		try {
			InputStream is = this.context.getAssets().open(DB_NAME); // 欲导入的数据库
			FileOutputStream fos = new FileOutputStream(dbfile);
			byte[] buffer = new byte[BUFFER_SIZE];
			int count = 0;
			while ((count = is.read(buffer)) > 0) {
				fos.write(buffer, 0, count);
			}
			fos.close();
			is.close();
		} catch (Exception e) {

		}
	}

	private SQLiteDatabase openDatabase(String dbfile) {
		try {
			// 判断数据库文件是否存在，若不存在则执行导入，否则直接打开数据库
			if (!(new File(dbfile).exists())) {
				copyDatabase(dbfile);
			}
			SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
			return db;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public void closeDatabase() {
		this.database.close();
	}
}